<?php
namespace app\service\data;

use app\service\models\SystemUser;
use app\lib\Code;
use yii;

class SystemData
{
    
    private $dsUser;
    
    public function __construct()
    {
        $this->dsUser = new SystemUser();
    }
    
    /**
     * 用户登录
     *
     * @param array $arrInput
     * @return
     */
    public function UserLogin($arrInput) {
        $userInfo =  $this->findByUsername($arrInput['username']);
        if (empty($userInfo))  {
            formatJson(Code::SYS_USER_NOT_FIND);
        } elseif ($userInfo['is_close']== 1) {
            formatJson(Code::PARAM, "该账户已被禁用，请联系管理员");
        } else {
            //验证密码
            $is_true = $this->validatePassword($arrInput['password'], $userInfo['password']);
//             return $is_true;
        }
        
        $returnParam=$returnParam=['id'=>$userInfo['id'],'username'=>$userInfo['username'],'role'=>$userInfo['role']];
        Yii::$app->session->set('userInfo',$returnParam);
        return $returnParam;
    }
    
    /**
     * 验证密码
     *
     * @param string $password
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password, $dbPassword)
    {
        return \Yii::$app->security->validatePassword($password, $dbPassword);
    }
    
    /**
     * 根据登录名获取用户信息
     *
     * @param string $username
     * @return Ambigous <\yii\db\static, \yii\db\null>
     */
    public function findByUsername($username)
    {
        $res= $this->dsUser->findOne([
            'username' => $username,
            'is_del' => 0
        ]);
        return $res?$res->toArray():[];
    }
    
    /**
     * 添加管理员
     *
     * @param unknown $data
     * @return unknown
     */
    public function AddManager($data)
    {
        $query = $this->dsUser->find();
        $query->where([
            'username' => $data['username'],
            'is_del' => 0
        ]);
        if (! empty($data['id'])) {
            $query->andWhere("id!='{$data['id']}'");
        }
        $userInfo = $query->all();
        // 如果不等于本ID
        if (! empty($userInfo)) {
            formatJson(Code::PARAM, "用户名已经存在");
        }
        if (! empty($data['id'])) {
            $user = $this->dsUser->findOne($data['id']);
        } else {
            $user=$this->dsUser;
            $user->create_time=date("Y-m-d H:i:s");
        }
        $user->username = $data['username'];
        if (! empty($data['password'])) {
            $user->password = $data['password'];
        }
        $save = $user->save();
        return $save;
    }
    
    /**
     * 删除管理员
     */
    public function DelManager($manager_id)
    {
        $userObj = $this->dsUser->findOne($manager_id);
        if($userObj->role==1){
            return -1;
        }
        $userObj->is_del = 1;
        $save = $userObj->save();
        return $save;
    }
    
    /**
     * 修改管理员密码
     */
    public function ModifyManager($arrInput)
    {
        $userObj = $this->dsUser->findOne($arrInput['mid']);
        //超级管理员可改任何人账户
        if($userObj->role==1){
            $userInfo = $this->dsUser->findOne($arrInput['bid']);
            $userInfo->password= $arrInput['password'];
            $save = $userInfo->save();
        } elseif ($userObj->role==0 && $arrInput['mid'] == $arrInput['bid']) {
            $userInfo = $this->dsUser->findOne($arrInput['bid']);
            $userInfo->password= $arrInput['password'];
            $save = $userInfo->save();
        } else {
            formatJson(Code::PARAM, "没有权限");
        }
        return $save;
    }
    
    /**
     * 禁用管理员
     */
    public function CloseManager($manager_id)
    {
        $userObj = $this->dsUser->findOne($manager_id);
        if($userObj->role==1){
            return -1;
        }
        $userObj->is_close= 1;
        $save = $userObj->save();
        return $save;
    }
    
    /**
     * 开启管理员
     */
    public function OpenManager($manager_id)
    {
        $userObj = $this->dsUser->findOne($manager_id);
        if($userObj->role==1){
            return -1;
        }
        $userObj->is_close = 0;
        $save = $userObj->save();
        return $save;
    }
    
    /**
     * 管理员列表
     */
    public function ManagerList($arrInput) {
        $codition = ['is_del'=>'0'];
        $count = $this->dsUser
        ->find()
        ->where($codition)
        ->count();
        $ret = $this->dsUser
        ->find()
        ->where($codition)
        ->offset(($arrInput['page'] - 1) * $arrInput['page_size'])
        ->limit($arrInput['page_size'])
        ->all();
        
        $data_list = [];
        
        foreach ($ret as $value) {
            $data_list[] = $value->toArray([
                'id',
                'username',
                'create_time',
                'update_time',
                'is_close',
                'role',
            ]);
        }
        
        return [
            "total_size"=>intval($count),
            "page"=>$arrInput['page'],
            "page_size"=>$arrInput['page_size'],
            "data_list"=>$data_list,
        ];
    }
}
